﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include  <QPointer>
#include <QDebug>
#include <QJsonObject>
QObject *object;
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //实例化类变量
    server =new QTcpServer;//实例化
    socket=new  QTcpSocket;//实例化
    timer = new QTimer;
    connect(server,SIGNAL(newConnection()),this,SLOT(newconnected()));
    //实例化定时器槽函数
    connect(timer,SIGNAL(timeout()),this,SLOT(recvTimerOut()));


}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::newconnected()//客户端连接
{
    //实现客户端连接槽函数
    if(server->hasPendingConnections())

    {
        socket = server->nextPendingConnection();
        connect(socket,SIGNAL(readyRead()),this,SLOT(recvData()));
        connect(socket,SIGNAL(disconnected()),this,SLOT(disconnected()));
    }
}


void MainWindow::recvData()    //接收数据
{

    timer->start(2);
}
void MainWindow::recvTimerOut()//定时器槽函数
{
    //    //读取数据
    QByteArray sr =socket->readAll();
    socket->write(sr);
    ui->textEdit_TCP_Recv->insertPlainText(QString(sr));
    timer->stop();

}

void MainWindow::disconnected()//客户端断开
{

}
//实现数据读取和启动TCP服务器

void MainWindow::on_btn_TCP_Conn_clicked()//连接
{
    QString ip =ui->lineEdit_TCP_IP->text();
    int port =ui->lineEdit_TCP_PORT->text().toUInt();
    server->listen(QHostAddress(ip),port);
}



//添加onHttpAccepted回调函数
//HTTP服务器设置
void onHttpAccepted(const QPointer <JQHttpServer::Session> &session )
{
    //有客户端调用接口时，会调用该函数
    qDebug()<<session->requestUrl();//请求url信息

    //http://127.0.0.1:1234/
    qDebug()<<session->requestMethod();//get或Post请求
    qDebug()<<session->requestBody();//接口上传带的参数
    //    session->replyText("aa");
    QJsonObject json;
    json.insert("result","success");
    session->replyJsonObject(json);
    //post：上传信息，如注册
    //get：获取，如登录，控制设备
    //接口：
    // /api/login
    // /api/register
    // /api/controlDevice

    //发送事件
    CustomerEvent*customerEvent =new CustomerEvent(session);
    QCoreApplication::postEvent(object,customerEvent);
}
//实现initializeHttpServer函数

void MainWindow::initializeHttpServer(int port)
{
    static JQHttpServer::TcpServerManage tcpServerManage(10);
    tcpServerManage.setHttpAcceptedCallback(std::bind(onHttpAccepted,std::placeholders::_1));
    const auto listenSucceed = tcpServerManage.listen(QHostAddress::Any,port);
    qDebug()<<"start Listen:"<<listenSucceed;

}


//启动HTTP服务器
void MainWindow::on_btn_HTTP_Conn_clicked()
{
    int port =ui->lineEdit_HTTP_PORT->text().toUInt();
    initializeHttpServer(port);
}

//http
//处理客户端请求
bool MainWindow::event(QEvent *event) //接收并处理事件
{
    if(event->type()==CustomerEvent::eventType())//过滤自定义的事件
    {
        CustomerEvent* customerEvent = dynamic_cast<CustomerEvent*>(event);
        QPointer<JQHttpServer::Session> session = customerEvent->getSession();
        ui->textEdit_HTTP_Recv->append(session->requestBody());

    }
    return QMainWindow::event(event);
}
